package com.jake.rabbit.controller;

import com.jake.common.util.ThreadUtils;
import com.jake.rabbit.consumer.ResponseMapConsumer;
import com.jake.rabbit.producer.RequestMapProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

import static com.jake.common.constant.KeyConstants.*;
import static com.jake.common.constant.QueueConstants.REQUEST_QUEUE;

@RestController
@RequestMapping(value = "api")
@Slf4j
public class RabbitApiController {

    @Autowired
    private RequestMapProducer requestMapProducer;

    @Autowired
    private ResponseMapConsumer responseMapConsumer;

    @PostMapping(value = "data")
    public Map<String, Object> getResponseMap(@RequestBody Map<String, Object> requestMap) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String requestId = UUID.randomUUID().toString();
        int requestQueueNumber = RandomUtils.nextInt(1, 6);
        requestMap.put(REQUEST_ID, requestId);
        requestMap.put(REQUEST_QUEUE_NUMBER, requestQueueNumber);
        requestMapProducer.sendRequestMap(REQUEST_QUEUE + requestQueueNumber, requestMap);
        Map<String, Object> responseMap = responseMapConsumer.getResponseMap();
        while (CollectionUtils.isEmpty(responseMap)) {
            ThreadUtils.sleep(100);
            responseMap = responseMapConsumer.getResponseMap();
            stopWatch.stop();
            double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
            if (totalTimeSeconds > 2.0) {
                log.warn("目前耗时：{}", totalTimeSeconds);
                return getResponseMap(requestMap);
            }
            stopWatch.start();
        }
        String responseId = (String) responseMap.get(RESPONSE_ID);
        int responseQueueNumber = (int) responseMap.get(RESPONSE_QUEUE_NUMBER);
        while (!(StringUtils.equals(requestId, responseId) && requestQueueNumber == responseQueueNumber)) {
            ThreadUtils.sleep(100);
            responseMap = responseMapConsumer.getResponseMap();
            responseId = (String) responseMap.get(RESPONSE_ID);
            responseQueueNumber = (int) responseMap.get(RESPONSE_QUEUE_NUMBER);
        }
        return responseMap;
    }

}
